package com.hdy.javachatroomdemo.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdy.javachatroomdemo.Model.*;
import com.hdy.javachatroomdemo.constant.Constants;
import com.hdy.javachatroomdemo.factory.AbstractMessageTransfer;
import com.hdy.javachatroomdemo.factory.IMessageTransfer;
import com.hdy.javachatroomdemo.factory.MessageTransferFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
public class WebSocketController extends TextWebSocketHandler {
    //服务器进行消息的转发时,服务器只有userId,但是要能够获取到所有客户端对应的websocketSession
    //因此要将userId和websocketSession绑定起来,因此创建一个onlineUserMapper类
    //还有一个问题就是如何通过WebsocketSession拿到Httpsession对象来进行客户端判断
    //这里采用的方式是在handler类配置的时候添加一个拦截器
    @Autowired
    private OnlineUserMapper onlineUserMapper;
    @Autowired
    private SessionMapper sessionMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    FriendMapper friendMapper;
    @Autowired
    MessageTransferFactory messageTransferFactory;

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("websocket 连接关闭 ,关闭状态: "+status.toString());
        //先从websocketSession中把user对象取出来
        User user =(User) session.getAttributes().get(Constants.USER_SESSION);
        //先确保user对象不为空
        if(user==null){
            return;
        }
        onlineUserMapper.remove(user,session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //不管是正常断开连接还是异常断开,都要删除映射关系
        System.out.println("websocket 连接异常 ,异常状态: "+exception.toString());
        //先从websocketSession中把user对象取出来
        User user =(User) session.getAttributes().get(Constants.USER_SESSION);
        //先确保user对象不为空
        if(user==null){
            return;
        }
        onlineUserMapper.remove(user,session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("websocket 接受消息 ,消息内容: "+message.toString());
        //服务器接收到客户端发来的请求时用messageRequest保存起来
        //此处接收到的message是个字符串,需要转成对象
        ObjectMapper mapper = new ObjectMapper();
        MessageRequest request = mapper.readValue(message.getPayload(),MessageRequest.class);
        //判断载荷是不是消息类型
        User user =(User)session.getAttributes().get(Constants.USER_SESSION);
        if(user==null){
            System.out.println("[WebSocketController:handleTextMessage]:user对象为空");
            return;
        }
        IMessageTransfer messageTransfer=messageTransferFactory.getTransfer(request.getType());
        messageTransfer.send(request,user);
//        if(request.getType().equals(Constants.MESSAGE)){
//            //为消息类型时
//            //获取userId
//
//            //接着进行对象的转发
//            transferMessage(request,user);
//        }else if(request.getType().equals(Constants.FRIEND_REQUEST)){
//            //为好友请求时
//            User user =(User)session.getAttributes().get(Constants.USER_SESSION);
//            if(user==null){
//                System.out.println("[WebSocketController:handleTextMessage]:user对象为空");
//                return;
//          }
//            transferFriendRequest(request,user);
//        }
//        else{
//            System.out.println("websocket载荷类型错误!");
//        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("websocket 连接建立 ");
        //先从websocketSession中把user对象取出来
        User user =(User) session.getAttributes().get(Constants.USER_SESSION);
        //先确保user对象不为空
        if(user==null){
            return;
        }
        //添加映射
        onlineUserMapper.add(user,session);
    }
}
